package com.cookbook;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @author 毛川
 */
public class Result<DataType> {
    public static final int OK = 0;

    public static final int PARAMETER_INVALID = 400;
    public static final int USERNAME_NOT_EXISTS = 401;
    public static final int PASSWORD_INVALID = 402;
    public static final int USERNAME_EXISTS = 403;
    public static final int NOT_FOUND = 404;
    public static final int NO_PERMISSION = 405;
    public static final int AUTHORITY_EXPIRED = 406;
    public static final int PERMISSION_ERROR = 407;
    public static final int FILE_SUFFIX_NOT_SUPPORTED = 408;

    public static final int INTERNAL_ERROR = 500;

    private int code;
    private String message;
    private DataType data;

    private Result(int code, String message, DataType data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> String format(int code, String message, T data) {
        Result<T> result = new Result<T>(code, message, data);

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss") //按照 yyyy-MM-dd HH:mm:ss格式化。
                .create();
        return gson.toJson(result);
    }

    public static String format(int code, String message) {
        return format(code, message, null);
    }

    public static <T> String success(T data) {
        return format(OK, "OK", data);
    }
}
